package cn.iocoder.yudao.module.alipay.util;

import com.alipay.api.CertAlipayRequest;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@Slf4j
public class Tool {

	public static java.util.Date parseDate(String dateStr, String format) {
		java.util.Date date = null;
		try {
			java.text.DateFormat df = new java.text.SimpleDateFormat(format);
			String dt = dateStr.replaceAll("-", "/");
			if ((!dt.equals("")) && (dt.length() < format.length())) {
				dt += format.substring(dt.length()).replaceAll("[YyMmDdHhSs]",
						"0");
			}
			date = (java.util.Date) df.parse(dt);
		} catch (Exception e) {
		}
		return date;
	}

	public static java.util.Date parseDate(String dateStr) {
		return parseDate(dateStr, "yyyy-MM-dd");
	}

	public static long getMillis(java.util.Date date) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}

	public static java.util.Date addDate(java.util.Date date, int day) {
		java.util.Calendar c = java.util.Calendar.getInstance();
		c.setTimeInMillis(getMillis(date) + ((long) day) * 24 * 3600 * 1000);
		return c.getTime();
	}

	public static String md5(String str) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");

			messageDigest.reset();

			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.out.println("NoSuchAlgorithmException caught!");
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		return md5StrBuff.toString();
	}

	public static String encodeUri(String url) {

		try {
			return java.net.URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {

			e.printStackTrace();
		}
		return url;
	}

	public static String encryptDES(String message, String key) throws Exception {
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

		return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
	}

	public static String decryptDES(String message, String key) throws Exception {

		byte[] bytesrc = convertHexString(message);
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

		byte[] retByte = cipher.doFinal(bytesrc);
		return new String(retByte);
	}

	public static byte[] convertHexString(String ss) {
		byte digest[] = new byte[ss.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = ss.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}

		return digest;
	}

	public static String toHexString(byte b[]) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String plainText = Integer.toHexString(0xff & b[i]);
			if (plainText.length() < 2)
				plainText = "0" + plainText;
			hexString.append(plainText);
		}

		return hexString.toString();
	}
	
	/**
	 * 
	 * 返回0到9到的n位随机数 
	 *
	 * @param n
	 * @return
	 */
	public static String getRandomNumber(int n){
		if(n < 1){
			return "";
		}
		
		StringBuilder sb = new StringBuilder();
		Random ra =new Random();
		for(int i=0; i<n;i++){
			sb.append(ra.nextInt(10));
		}
		return sb.toString();
	}

	/*public static CertAlipayRequest getRequest(){
	 *//* 初始化 **//*
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		*//* 支付宝网关 **//*
		certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
		*//* 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **//*
		certAlipayRequest.setAppId("2021004101664460");
		*//* 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport **//*
		certAlipayRequest.setPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCNmpF/ciDWmM8HW1Bd6mp6oK7P6dgFhVwIRfCSTFaRH2MYu8wbRR1yPKKUX+glz/o/JZIiJQpVB1QgtnUgk1JSjOXvGIPZuDvG5czkSmZPBH4zSXK7i8px6PyxfzsPF8WATHBKL129ATYv+fNoe9TKUzAyo5RkEOmcFkdQ1lGPmxmcppGDuqWf9hAA6+CFHpFdPAk5v/HK5JrqY7+68R/aTU1/gG79m82B/EfkYoJYhfORgk6qFu5WsK0ZlP3gdwtEyr0YUATx4g/fO7dgSlu3nsJRCLNTGDaIGF6+7urynDBCtF/Rh6wNG6AKVW1W5t/OO/3OAtYkpCiHHTeQMTnFAgMBAAECggEAN0svG3v+VK3Q0ceXZ0TdFUtfV7Kxdt5vZI+i9A25E+wUrxjOB6wCZpREy/lzViiTSEsseAbMtQ0qjaeRrwm38KIyOx3whnjJZs5fJpniv2I6wV4h3hglEjvvSIQtFKSsq3+trVo3mVE6zpsksB0Cp4q6XFvB2x07i4arjGZT7OYGT3dgAxw6m6r6Hr0kQJ826z0/JyYayMHQJJ03BS+uzNBHzxTQIsv0FPRSPmz4iuHw+AiYQLeBj5eyQDXUJsxOv8NbebnOcTrl0QJJM3xh3Zz8D8k+WnYwYkKRngc6ErhHbjGw3KhotBofakR13wk0PLLjffKKkDd8tYv3XHKbVQKBgQDc77zjUjIl9d24QkMm6fRbQDkRCN0nSyIG/MR4nC5iOCOgZh0V1F1TrvYJhlMh8Rj+SNCpAQ8sc3UZQ+9mbZ7R02jKsxMwYbGgEizrRA2Usn5MFDaQZQhY5aCNuwprbaQU8r+NDKHi8tJ9hUB3WYQdUODpPcjWtEhKMjr2CXrRbwKBgQCkE66daakXzIgGLc434gPfW7jUWrpgohsuFACJIR1QD1myYy2EZnRlY1dR9PNyc6pC3IpPd4PrEjToHXim9TIj+YJn5+u1ysQyvY+zVXjBRy54VKLbwgLVLVt6THrKOejFETkbVMaFXR70cJNvGO9JUWtIu73UPHM6OToyowhmCwKBgQCyeSOACq0iBxxFtZljfQh9EkNHJH7qOAJT3Kqlt5yskScOco66TKPbbvGnvg+30nhbKd0NOSLVyKrmbv+cIZ9zZrE3VTOCGNkRMr2Ai6fg39Owh3+QY1072rs44shHAfnTRklAmtzHZVpuNU9fWjukJuqY3+U2s8nVzf/dMsk5FwKBgBIZLbClYAaFBBgSY2Xco2q21ltuKpLQLslVYX2+zlnvZ4h60iGBn6MzYwViTJw6T/SSGRuM5ls+peFYpt9buo0nT5Agj+p8lEm4iSpR6kD/lgul4lT1QJS9LRL/bqfx3VAnhzIRlthNHkX+SPT/Ph3LQldChjzr8hXhDB9bxmhjAoGBAJdakks0XYlDinIanr3eYV9Qbietc8klwbCSEwkuWKfy3vL55xWdodIcPonfTGlTgjwc2DYW0/ZTH3GGN7phVmPXSm0q3aeC5gInAQG9e8Wq6dxho7tt8534Kcxr5oxM0DBS1qUXHQevtV3E6YYgJX5Vki0uzdT4VTzV70KP2mQq");
		*//* 应用公钥证书路径，下载后保存位置的绝对路径 **//*
	 *//*	certAlipayRequest.setCertPath("H:/alipay/key20230801134938/appCertPublicKey.crt");
	 *//**//* 支付宝公钥证书路径，下载后保存位置的绝对路径 **//**//*
		certAlipayRequest.setAlipayPublicCertPath("H:/alipay/key20230801134938/alipayCertPublicKey_RSA2.crt");
		*//**//* 支付宝根证书路径，下载后保存位置的绝对路径 **//**//*
		certAlipayRequest.setRootCertPath("H:/alipay/key20230801134938/alipayRootCert.crt");*//*

		certAlipayRequest.setCertPath("/var/javaApp/alipay/key20230801134938/appCertPublicKey.crt");
		certAlipayRequest.setAlipayPublicCertPath("/var/javaApp/alipay/key20230801134938/alipayCertPublicKey_RSA2.crt");
		certAlipayRequest.setRootCertPath("/var/javaApp/alipay/key20230801134938/alipayRootCert.crt");

		*//* 设置签名类型 **//*
		certAlipayRequest.setSignType("RSA2");
		*//* 设置请求格式，固定值json **//*
		certAlipayRequest.setFormat("json");
		*//* 设置编码格式 **//*
		certAlipayRequest.setCharset("UTF-8");
		return certAlipayRequest;
	}*/

	public static CertAlipayRequest getRequest(){
		String appid = "2021004113609008";
		String privateKey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCMchdIIs5dLwW5lu4KvGENtQ6EeQCp5DDXdhag+iFdKMKtLJBFEWMEnTQ056MclGYKaINsgJ5Lz+2necbKMpsRHZLv/V7Nl30QY1kvdBKhNkHCrLH5iXNNjYRI5EVwC3DKOjS/TcxUaIezBQS0fHv+A0bXqinIDYFLp2T8INm85zxJ1DTzzDv3NKp9lkf1pDMIRpqfSve1qMwxyyXTGlnhGBwb8K0ZI9k8OxD+9Vvb21NuuaaL81VswN1rgovXCnnmkAbSD9u7QJ8n2rIsmi/rZ95+6DxF+07axYaR/EbRVj6fA4RPKxMthbl/5WLGuUY9iEqH4vqn1y3X9TvGfqdxAgMBAAECggEACsDpm3Jezq+9BnrR+yx1WfFVDTuem2OHgdfe37CHQXTPgyb4XPF53W6UAsEBsjyCm6Vo+rPWawOetMYUPIMncGYNTCbgTWmd/9U7jPCcRI+89UT30518oKGHUXV5A508o59VTpiMXqIqUcC+nXsymz5w/C5hSJoQHlTQ3KU/RsFnhcESKLb5yBOH/UckTrwOrxhMRsHi1edFfp47DilN6abKV+KzwbFQwLpoze7TQh/YPq+LbhWTWi46xHkDnfBQIJ1Vh9aZt8tB4qysTu0RxdmXMpVNzqoqQ9ux8mOzpVNYKmkJ8IUkNz3xcSGhk1y85pwwO04HqNxLFDcVuLGkyQKBgQD+XQ1z+d2MkxLpIT5fL87Rmt1fwd0lTPO+lExt0EUao1H1Zk7kSrIWB80mf8mUYyopx/9pqfWgTRdrdyuGAbLUC86rn5tPysKnW598l+k+tgSStgx5C0WHEcVkUaIUxc0J6bcOiEsjnUNsSNR878b0llQGywWcy5dPDI8ZuIqIYwKBgQCNWWkxu7yPzzL+2FuAZk/zlNj84JVubX9QC0vSNqWyLvGD7tGn7oetQ/snMFGSkfCbsl61Zv2IPeKI+l76DQ5IcoFf1K43vgnE4w7ggYpws9a+W8KKZhNMBLERg4H8hwwJqbUgtD/pN8neQDG3XTSgdKR1Jb2v84Pt3pKfXKc3GwKBgFjiQVI2jQGTXzdR4461kQrTl+nfP5zKMB53ieGRtqQhUAF1t7m0lFh4b2q1msYchN5Gwey1dFyIs9dctDvGmivY2GZGhqoySyTaMngCSYIdbqmpreAaXThesGBm2kFyAT0mi04ruD4AtU/Af2gNDbPoWAJrrVFmH0CDPfoZ72bLAoGAYghJ8gk/vQm6V4+c3o+XEdwBJlloqj7dFpnPC0uFXfA65wLie7LufJfyf3p+iMYY9xMdpnh4jF5HWDM1Xf1iE5L+8YTjE5wE0H2d2s1dQ88mt72STkR/S7DRUdFAfPD4w1blXXpF/S0JH9Cr6n2FO2fKi8kSJw8gSACe9lHfU1MCgYAu9mP5U19scc/WlXBASqhjeTRSKujCh1f6oCPx3Yqj4fqN3tDWnE4zMB9MNNrf8Mt10Um5MMmVCFqvqL19rHKo258oES4PNsgEigEh7CpS9wxamYLBZ2sXIdNy2NYCv7P3AnM8ENMNuBX3MbBuTz2l2nhqeLGWPnR2q28qsGzHJw==";
       /* 初始化 **/
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		/* 支付宝网关 **/
		certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
		/* 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
		certAlipayRequest.setAppId(appid);
		/* 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport **/
		certAlipayRequest.setPrivateKey(privateKey);
		/* 应用公钥证书路径，下载后保存位置的绝对路径 **/
	/*	certAlipayRequest.setCertPath("H:/alipay/key20230801134938/appCertPublicKey.crt");
		*//* 支付宝公钥证书路径，下载后保存位置的绝对路径 **//*
		certAlipayRequest.setAlipayPublicCertPath("H:/alipay/key20230801134938/alipayCertPublicKey_RSA2.crt");
		*//* 支付宝根证书路径，下载后保存位置的绝对路径 **//*
		certAlipayRequest.setRootCertPath("H:/alipay/key20230801134938/alipayRootCert.crt");*/

		certAlipayRequest.setCertPath("/var/javaApp/alipay/key20230829104123/appCertPublicKey_2021004113609008.crt");
		certAlipayRequest.setAlipayPublicCertPath("/var/javaApp/alipay/key20230829104123/alipayCertPublicKey_RSA2.crt");
		certAlipayRequest.setRootCertPath("/var/javaApp/alipay/key20230829104123/alipayRootCert.crt");
		/* 设置签名类型 **/
		certAlipayRequest.setSignType("RSA2");
		/* 设置请求格式，固定值json **/
		certAlipayRequest.setFormat("json");
		/* 设置编码格式 **/
		certAlipayRequest.setCharset("UTF-8");
		return certAlipayRequest;
	}

	public static CertAlipayRequest getRequestTemplate(){
		String appid = "2021004134651039";
		String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCh3QjvlnWpOnDez+N7/GRxIM21j5Kp1TjBcVXfKUM1Wp8dFIt33cKKM11fb2XNgh142a+REDAlcFbby39oWQHzC5c/GwHnc8BTr2hc6OMFMD67OzEI7reEP/IfPodcCVP/Vg9Co4/VcvVrwsUMN45x/Mpg/t/hEIB2RyD03e9IKEbWFjklddRpdgJbEe6NurPQDgGMFaAbpEZZ1+FNUlBBgNAZCDYeaCtSkqQUvHMUbtHoPcMeN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vcx5eRfzZkeObEvK9WkvF5zfs3RI3TAMT04WcH/Sy7GWc8slDfv6M014s8T9y3/0Ef1HXFouAe4roXFR5SthIrSJAoGBAJ/MxiJ8NnPt5t+D9kCfTh6+WkoK/s6CyV5CRS9L15lrsx5/Jp39cX07/LcFgTOQSEq6tLJW7TlCJfhDdq9orZiOrrZ5BcWDxEJpKISq0OWLvGA9sJ9Y5u4JCJmdJphc4iSB0F8ls9xUnkGf7toFaP0StrI0tltGvkAHUrfC2psy";
		/* 初始化 **/
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		/* 支付宝网关 **/
		certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
		/* 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
		certAlipayRequest.setAppId(appid);
		/* 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport **/
		certAlipayRequest.setPrivateKey(privateKey);
		/* 应用公钥证书路径，下载后保存位置的绝对路径 **/
		/*	certAlipayRequest.setCertPath("H:/alipay/key20230801134938/appCertPublicKey.crt");
		 *//* 支付宝公钥证书路径，下载后保存位置的绝对路径 **//*
		certAlipayRequest.setAlipayPublicCertPath("H:/alipay/key20230801134938/alipayCertPublicKey_RSA2.crt");
		*//* 支付宝根证书路径，下载后保存位置的绝对路径 **//*
		certAlipayRequest.setRootCertPath("H:/alipay/key20230801134938/alipayRootCert.crt");*/
/*		String app_cert_path = "D:/gitee/cert/key20240210105508/appCertPublicKey_2021004134651039.crt";
		String alipay_cert_path = "D:/gitee/cert/key20240210105508/alipayCertPublicKey_RSA2.crt";
		String alipay_root_cert_path = "D:/gitee/cert/key20240210105508/alipayRootCert.crt";*/
		String app_cert_path = "/var/javaApp/alipay/key20240210105508/appCertPublicKey_2021004134651039.crt";
		String alipay_cert_path = "/var/javaApp/alipay/key20240210105508/alipayCertPublicKey_RSA2.crt";
		String alipay_root_cert_path = "/var/javaApp/alipay/key20240210105508/alipayRootCert.crt";

		certAlipayRequest.setCertPath(app_cert_path);
		certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
		certAlipayRequest.setRootCertPath(alipay_root_cert_path);
		/* 设置签名类型 **/
		certAlipayRequest.setSignType("RSA2");
		/* 设置请求格式，固定值json **/
		certAlipayRequest.setFormat("json");
		/* 设置编码格式 **/
		certAlipayRequest.setCharset("UTF-8");
		return certAlipayRequest;
	}

}
